#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define N 128

int main(int argc, char const *argv[])
{
    int fd1, fd2, fd3;
    int ch,ret;
    if (argc != 4)
    {
        fprintf(stderr, "运行程序时，请带入参数 ./10-fseek file1 file2 file3 \n");
        exit(-1);
    }
    //
    
    fd1 = open(argv[1], O_RDONLY|O_EXCL);
    if (fd1 < 0)
    {
        perror("fd1:open");
        exit(-1);
    }
    fd2 = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC,0664);
    if (fd2 < 0)
    {
        perror("fd2:open");
        exit(-1);
    }
    fd3 = open(argv[3], O_WRONLY|O_CREAT|O_TRUNC,0664);
    if (fd3 < 0)
    {
        perror("fd3:open");
        exit(-1);
    }

    //把文件位置设置到文件末尾
    long file_pos = lseek(fd1,0,SEEK_END);//获取文件位置的返回值，就是文件的大小
    lseek(fd1,0,SEEK_SET);
    for (long i = 0; i < file_pos/2; i++)
    {
        ret = read(fd1,&ch,1);
        if (ret < 0)
        {
            perror("read");
            exit(-1);
        }
        ret = write(fd2,&ch,1);
        if (ret < 0)
        {
            perror("write");
            exit(-1);
        }
    }

    for (long i = file_pos/2; i < file_pos; i++)
    {
        ret = read(fd1,&ch,1);
        if (ret < 0)
        {
            perror("read");
            exit(-1);
        }
        ret = write(fd3,&ch,1);
        if (ret < 0)
        {
            perror("write");
            exit(-1);
        }
    }
    
    close(fd1);
    close(fd2);
    close(fd3);
/*
    int fp1,fp2,fp3;
    char buf[N]={0};
    if (argc != 4)
    {
        fprintf(stderr, "运行程序时，请带入参数 ./16-fseek file1 file2 file3 \n");
        exit(-1);
    }
    //
    
    fp1 = open(argv[1], O_RDONLY|O_EXCL);
    if (fp1 == 0)
    {
        perror("open");
        exit(-1);
    }
    fp2 = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC,0664);
    if (fp2 == 0)
    {
        perror("open");
        exit(-1);
    }
    fp3 = open(argv[3], O_WRONLY|O_CREAT|O_TRUNC,0664);
    if (fp3 == 0)
    {
        perror("open");
        exit(-1);
    }
 
    long file_pos = lseek(fp1,0,SEEK_END);//把文件位置设置到文件末尾
    //;//获取文件位置的返回值，就是文件的大小
    lseek(fp1,0,SEEK_SET);
        for (long i = 0; i < file_pos/2; i++)
    {
        //fputc(fgetc(fp1),fp2);
        write(fp2,buf,read(fp1,buf,1));
    }

    for (long i = file_pos/2; i < file_pos; i++)
    {
        //write(fp3,buf,i);
        write(fp3,buf,read(fp1,buf,1));
    }
    
    close(fp1);
    close(fp2);
    close(fp3);
*/
    return 0;
}
